package com.petdog.module.user.service.impl;

import com.petdog.infrastructure.entity.User;
import com.petdog.infrastructure.mapper.UserMapper;
import com.petdog.module.user.service.UserService;
import com.petdog.common.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        
        // 检查用户状态
        if (user.getStatus() != null && user.getStatus() != 1) {
            throw new UsernameNotFoundException("用户状态异常: " + username);
        }
        
        // 创建用户认证信息
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
        );
    }
    
    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }
    
    @Override
    public User getUserById(Long userId) {
        return userMapper.selectById(userId);
    }
    
    @Override
    public User registerUser(User user) {
        // 检查用户名是否已存在
        if (existsByUsername(UserUtils.getUsername(user))) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        String email = UserUtils.getEmail(user);
        if (email != null && !email.isEmpty() && existsByEmail(email)) {
            throw new RuntimeException("邮箱已被注册");
        }
        
        // 检查手机号是否已存在
        String phone = UserUtils.getPhone(user);
        if (phone != null && !phone.isEmpty() && existsByPhone(phone)) {
            throw new RuntimeException("手机号已被注册");
        }
        
        // 加密密码
        UserUtils.setPassword(user, passwordEncoder.encode(UserUtils.getPassword(user)));
        
        // 设置默认值
        UserUtils.setCreateTime(user, LocalDateTime.now());
        UserUtils.setUpdateTime(user, LocalDateTime.now());
        UserUtils.setStatus(user, 1); // 默认为启用状态
        UserUtils.setRole(user, 1); // 默认为普通用户角色
        UserUtils.setLoginCount(user, 0);
        UserUtils.setEmailVerified(user, false);
        UserUtils.setPhoneVerified(user, false);
        
        // 插入用户
        userMapper.insert(user);
        
        return user;
    }
    
    @Override
    public User updateUser(User user) {
        if (UserUtils.getUserId(user) == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        
        // 检查用户是否存在
        User existingUser = userMapper.selectById(UserUtils.getUserId(user));
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 更新时间
        UserUtils.setUpdateTime(user, LocalDateTime.now());
        
        // 更新用户信息
        userMapper.update(user);
        
        return userMapper.selectById(UserUtils.getUserId(user));
    }
    
    @Override
    public void updateLoginInfo(Long userId, String ip) {
        userMapper.updateLoginInfo(userId, LocalDateTime.now(), ip);
    }
    
    @Override
    public boolean existsByUsername(String username) {
        return userMapper.selectByUsername(username) != null;
    }
    
    @Override
    public boolean existsByEmail(String email) {
        return userMapper.selectByEmail(email) != null;
    }
    
    @Override
    public User getUserByEmail(String email) {
        return userMapper.selectByEmail(email);
    }
    
    @Override
    public boolean existsByPhone(String phone) {
        return userMapper.selectByPhone(phone) != null;
    }
}
